package com.jiang.core.common;

import com.jiang.core.enums.BusinessCode;
import com.jiang.core.enums.ErrorCode;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

import java.io.Serializable;

/**
 * \* 作者: jiang
 * \* 时间: 2021/5/23 17:37
 * \* 描述: 后端返回给前段的格式化数据结构
 * \
 */
@ApiModel
@Data
public class MSG<T> implements Serializable {

    private final static int SUCCESS_CODE = 0;
    private final static String SUCCESS_MESSAGE = "操作成功";

    private final static int BUSINESS_CODE = 1;
    private final static String BUSINESS_MESSAGE = "业务特殊处理";

    private final static int ERROR_CODE = -1;
    private final static String ERROR_MESSAGE = "操作失败";

    // 状态码 0-标识成功, 非0-标识失败
    @ApiModelProperty(value = "状态码 0-标识成功, 小于0-标识失败, 大于0-特定业务操作逻辑")
    private int code;
    // 提示信息
    @ApiModelProperty(value = "提示信息")
    private String message;
    // 数据内容
    @ApiModelProperty(value = "返回内容")
    private T content;

    // 构造函数私用
    private MSG(){}


    /**
     * 创建一条消息
     *
     * @param code 状态码
     * @param message 提示信息
     * @param content 数据内容
     * @return MSG
     */
    private static <T> MSG<T> createMSG(int code, String message, T content){
        MSG<T> msg = new MSG<>();
        msg.code = code;
        msg.message = message;
        msg.content = content;
        return msg;
    }

    /**
     * 创建一条消息,无消息内容
     *
     * @param code 状态码
     * @param message 提示信息
     * @return MSG
     */
    private static <T> MSG<T> createMSG(int code, String message){
        return createMSG(code, message, null);
    }


    // 操作成功返回的MSG
    public static <T> MSG<T> SUCCESS(){
        return MSG.createMSG(SUCCESS_CODE, SUCCESS_MESSAGE);
    }

    public static <T> MSG<T> SUCCESS(boolean success){
        return success ? SUCCESS() : ERROR();
    }

    public static <T> MSG<T> SUCCESS(T content){
        return MSG.createMSG(SUCCESS_CODE, SUCCESS_MESSAGE, content);
    }

    public static <T> MSG<T> SUCCESS(String message, T content){
        return MSG.createMSG(SUCCESS_CODE, message, content);
    }


    // 需要特殊处理的业务的MSG
    public static <T> MSG<T> BUSINESS(BusinessCode businessCode){
        return MSG.createMSG(businessCode.getValue(), businessCode.getDesc());
    }

    public static <T> MSG<T> BUSINESS(BusinessCode businessCode, T content){
        return MSG.createMSG(businessCode.getValue(), businessCode.getDesc(), content);
    }


    // 操作失败返回的MSG
    public static <T> MSG<T> ERROR(){
        return MSG.createMSG(ERROR_CODE, ERROR_MESSAGE);
    }

    public static <T> MSG<T> ERROR(ErrorCode errorCode){
        return MSG.createMSG(errorCode.getValue(), errorCode.getDesc());
    }

    public static <T> MSG<T> ERROR(int code, String message){
        return MSG.createMSG(code, message);
    }

    public static <T> MSG<T> ERROR(ErrorCode errorCode, String message){
        return MSG.createMSG(errorCode.getValue(), message);
    }
}